from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import logging

from datetime import datetime, timedelta
import database
import scraper
import os

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 确保日志目录存在
log_dir = "log/"
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.FileHandler(os.path.join(log_dir, "weather_api.log")), logging.StreamHandler()]
)
logger = logging.getLogger("weather_api")

# 初始化数据库
database.init_database()


@app.route('/api/cities', methods=['GET'])
def get_cities():
    """获取所有可用城市"""
    try:
        cities = database.get_available_cities()
        return jsonify({
            "status": "success",
            "count": len(cities),
            "cities": cities
        })
    except Exception as e:
        logger.error(f"Error getting cities: {e}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


@app.route('/api/weather/current', methods=['GET'])
def get_current_weather():
    """获取当前天气"""
    city = request.args.get('city')

    if not city:
        return jsonify({
            "status": "error",
            "message": "City parameter is required"
        }), 400

    try:
        # 获取今天的日期
        today = datetime.now().strftime("%Y-%m-%d")

        # 查询数据库
        weather = database.get_city_weather(city, today)

        # 如果没有今天的数据，尝试抓取
        if not weather:
            logger.info(f"No current data for {city}, trying to scrape...")
            current_month = datetime.now().strftime("%Y%m")
            scraper.scrape_city_weather(city, [current_month])
            database.load_json_to_db()
            weather = database.get_city_weather(city, today)

        if weather:
            return jsonify({
                "status": "success",
                "city": city,
                "date": today,
                "weather": weather
            })
        else:
            # 如果仍然没有，返回最新的数据
            latest_data = database.get_city_weather(city)
            if latest_data and len(latest_data) > 0:
                return jsonify({
                    "status": "success",
                    "city": city,
                    "date": latest_data[0]['date'],
                    "weather": latest_data[0],
                    "note": "Current data not available, showing latest available data"
                })
            else:
                return jsonify({
                    "status": "error",
                    "message": f"No weather data available for {city}"
                }), 404

    except Exception as e:
        logger.error(f"Error getting current weather: {e}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


@app.route('/api/weather/history', methods=['GET'])
def get_weather_history():
    """获取历史天气数据"""
    city = request.args.get('city')
    start_date = request.args.get('start_date')
    end_date = request.args.get('end_date')

    if not city:
        return jsonify({
            "status": "error",
            "message": "City parameter is required"
        }), 400

    try:
        conn = sqlite3.connect(database.DB_FILE)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()

        query = "SELECT * FROM weather WHERE city = ?"
        params = [city]

        if start_date:
            query += " AND date >= ?"
            params.append(start_date)

        if end_date:
            query += " AND date <= ?"
            params.append(end_date)

        query += " ORDER BY date"

        cursor.execute(query, params)
        rows = cursor.fetchall()
        conn.close()

        weather_data = [dict(row) for row in rows]

        return jsonify({
            "status": "success",
            "city": city,
            "count": len(weather_data),
            "data": weather_data
        })

    except Exception as e:
        logger.error(f"Error getting weather history: {e}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


@app.route('/api/weather/month', methods=['GET'])
def get_monthly_weather():
    """获取月度天气数据"""
    city = request.args.get('city')
    month = request.args.get('month')  # 格式: YYYYMM

    if not city:
        return jsonify({
            "status": "error",
            "message": "City parameter is required"
        }), 400

    if not month:
        # 默认使用当前月份
        month = datetime.now().strftime("%Y%m")

    try:
        # 构建月份的开始和结束日期
        year = int(month[:4])
        mon = int(month[4:6])

        # 计算该月的第一天和最后一天
        first_day = datetime(year, mon, 1).strftime("%Y-%m-%d")

        if mon == 12:
            last_day = datetime(year + 1, 1, 1) - timedelta(days=1)
        else:
            last_day = datetime(year, mon + 1, 1) - timedelta(days=1)

        last_day = last_day.strftime("%Y-%m-%d")

        # 查询数据库
        conn = sqlite3.connect(database.DB_FILE)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()

        cursor.execute(
            "SELECT * FROM weather WHERE city = ? AND date >= ? AND date <= ? ORDER BY date",
            (city, first_day, last_day)
        )

        rows = cursor.fetchall()
        conn.close()

        weather_data = [dict(row) for row in rows]

        # 如果没有数据，尝试抓取
        if len(weather_data) == 0:
            logger.info(f"No data for {city} in {month}, trying to scrape...")
            scraper.scrape_city_weather(city, [month])
            database.load_json_to_db()

            # 再次查询
            conn = sqlite3.connect(database.DB_FILE)
            conn.row_factory = sqlite3.Row
            cursor = conn.cursor()

            cursor.execute(
                "SELECT * FROM weather WHERE city = ? AND date >= ? AND date <= ? ORDER BY date",
                (city, first_day, last_day)
            )

            rows = cursor.fetchall()
            conn.close()

            weather_data = [dict(row) for row in rows]

        return jsonify({
            "status": "success",
            "city": city,
            "month": month,
            "count": len(weather_data),
            "data": weather_data
        })

    except Exception as e:
        logger.error(f"Error getting monthly weather: {e}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


@app.route('/api/refresh', methods=['POST'])
def refresh_data():
    """手动刷新指定城市的天气数据"""
    if not request.json:
        return jsonify({
            "status": "error",
            "message": "Request must be JSON"
        }), 400

    city = request.json.get('city')
    months = request.json.get('months')

    if not city:
        return jsonify({
            "status": "error",
            "message": "City parameter is required"
        }), 400

    try:
        results = scraper.scrape_city_weather(city, months)
        database.load_json_to_db()

        return jsonify({
            "status": "success",
            "city": city,
            "results": results
        })

    except Exception as e:
        logger.error(f"Error refreshing data: {e}")
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500


@app.route('/api/weather', methods=['GET'])
def general_weather_query():
    """通用天气查询接口"""
    city = request.args.get('city')
    date = request.args.get('date')
    month = request.args.get('month')

    if not city:
        return jsonify({
            "status": "error",
            "message": "City parameter is required"
        }), 400

        # 根据参数决定调用哪个查询
    if date:
        # 查询特定日期
        try:
            weather = database.get_city_weather(city, date)

            if weather:
                return jsonify({
                    "status": "success",
                    "city": city,
                    "date": date,
                    "weather": weather
                })
            else:
                return jsonify({
                    "status": "error",
                    "message": f"No weather data available for {city} on {date}"
                }), 404
        except Exception as e:
            logger.error(f"Error in date query: {e}")
            return jsonify({
                "status": "error",
                "message": str(e)
            }), 500

    elif month:
        # 重定向到月度查询
        return get_monthly_weather()

    else:
        # 默认查询最近的天气
        try:
            weather_data = database.get_city_weather(city)

            if weather_data and len(weather_data) > 0:
                return jsonify({
                    "status": "success",
                    "city": city,
                    "count": len(weather_data),
                    "data": weather_data
                })
            else:
                return jsonify({
                    "status": "error",
                    "message": f"No weather data available for {city}"
                }), 404
        except Exception as e:
            logger.error(f"Error in general query: {e}")
            return jsonify({
                "status": "error",
                "message": str(e)
            }), 500


if __name__ == '__main__':
    # 确保数据库已初始化
    database.init_database()

    # 启动API服务
    app.run(debug=True, host='0.0.0.0', port=5000)  